﻿using System.Collections.Generic;
using System.Configuration;
using System.Web.Mvc;
using MovieDB.Common;
using MovieDB.Controllers.Common;
using MovieDB.DTOs;
using MovieDB.Models;
using MovieDB.ServiceInterfaces;

namespace MovieDB.Controllers
{
    public class SearchController : MovieBaseControler
    {
        private readonly ISearchService _searchService;
        private readonly int _pageSize;

        public SearchController(ISearchService searchService)
        {
            _searchService = searchService;
            _pageSize = int.Parse(ConfigurationManager.AppSettings["PageSize"]);
        }

        //
        // GET: /Search/
        [HttpGet]
        public JsonResult SearchByAutocomplete(string term)
        {
            IEnumerable<MovieDto> movies = _searchService.SearchForAutocomplete(term);
            var moviesForAutocomplete = Mapping.MapFromSourceToDestination<IEnumerable<MovieDto>, IEnumerable<AutocompleteItem>>(movies);

            return Json(moviesForAutocomplete, JsonRequestBehavior.AllowGet);
        }

        [HttpGet]
        public ActionResult Search(string id, int page = 0)
        {
            PagedMovieDto pagedMovieDto = _searchService.SearchByMoviename(id, page, _pageSize);
            
            var movieModels = Mapping.MapFromSourceToDestination<IEnumerable<MovieDto>, IEnumerable<MovieModel>>(pagedMovieDto.Movies);

            string pageBaseUrl = Url.Action("Search", "Search", new { id });
            var pagedMovieModel = ModelFactory.CreatePagedMovieModel(movieModels, pageBaseUrl, page, _pageSize, pagedMovieDto.TotalAmountOfMovies);

            ViewBag.SearchTerm = id;
            return View("Result", pagedMovieModel);
        }
    }
}